/*
 *  All rights Reserved, Designed By 翼虎能源
 *  Copyright:    Copyright(C) 2015-2015
 *  Company   北京翼虎能源科技有限公司
 *  @author 莫鹏
 *  @date  15-6-26 上午10:54
 *  @version 1.0
 *  @Description
 */

'use strict';
angular.module('DSLToolsApp', [
    'ui.router',
    'ui.bootstrap',
    'angular-confirm',
    'home',
    'toaster'
])
    .run(function ($rootScope, $state, $stateParams) {
        //把ui-router 相关状态保存到rootScope 方便使用
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;
    })
    .config(function ($stateProvider, $urlRouterProvider, $httpProvider) {

        $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

        $httpProvider.interceptors.push('httpResponsePermissionInterceptor');

        $urlRouterProvider.otherwise('/');

        $stateProvider
            .state('index', {
                url: "/",
                templateUrl: 'index.html',
                controller: 'indexCtrl'
            })
            .state('home', {
                url: "/home",
                templateUrl: 'view/home.html'
            })
            .state('home.template', {
                url: "/template",
                templateUrl: 'view/template.html'
            })
            .state('home.config', {
                url: "/config",
                templateUrl: 'view/config.html'
            })
            .state('home.newConfig', {
                url: "/newConfig",
                templateUrl: 'view/newConfig.html'
            })
        ;

    })
    .controller('indexCtrl', function ($scope, $state) {
        console.info("--------------------- init ----------------------");
        $state.go("home");
        console.info("--------------------- end ----------------------");
    })
    .factory('httpResponsePermissionInterceptor', function ($q, $location, $rootScope, $timeout, $log) {
        return {
            'responseError': function (rejection) {
                // do something on error
                if (rejection.status === 403 || rejection.status === 401) {
                    // http response status code 403 or 401 that means use has no permission
                    // here I redirect page to '/unauthorized',you can alse do anything you want

                    $log.info("httpResponsePermissionInterceptor, " + $location.path() + "," + rejection.status)
                    $rootScope.$state.go("login");

                    return $q.reject(rejection);
                }
                return $q.reject(rejection);
            }
        };
    })
    .factory('jQueryLikeParamSerializer', function () {
        function encodeUriQuery(val, pctEncodeSpaces) {
            return encodeURIComponent(val).
            replace(/%40/gi, '@').
            replace(/%3A/gi, ':').
            replace(/%24/g, '$').
            replace(/%2C/gi, ',').
            replace(/%3B/gi, ';').
            replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
        }
        function serializeValue(v) {
            if (angular.isObject(v)) {
                return angular.isDate(v) ? v.toISOString() : toJson(v);
            }
            return v;
        }

        function forEach(obj, iterator, context) {
            var key, length;
            if (obj) {
                if (angular.isFunction(obj)) {
                    for (key in obj) {
                        // Need to check if hasOwnProperty exists,
                        // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
                        if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
                            iterator.call(context, obj[key], key, obj);
                        }
                    }
                } else if (angular.isArray(obj) || isArrayLike(obj)) {
                    var isPrimitive = typeof obj !== 'object';
                    for (key = 0, length = obj.length; key < length; key++) {
                        if (isPrimitive || key in obj) {
                            iterator.call(context, obj[key], key, obj);
                        }
                    }
                } else if (obj.forEach && obj.forEach !== forEach) {
                    obj.forEach(iterator, context, obj);
                } else if (isBlankObject(obj)) {
                    // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
                    for (key in obj) {
                        iterator.call(context, obj[key], key, obj);
                    }
                } else if (typeof obj.hasOwnProperty === 'function') {
                    // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
                    for (key in obj) {
                        if (obj.hasOwnProperty(key)) {
                            iterator.call(context, obj[key], key, obj);
                        }
                    }
                } else {
                    // Slow path for objects which do not have a method `hasOwnProperty`
                    for (key in obj) {
                        if (hasOwnProperty.call(obj, key)) {
                            iterator.call(context, obj[key], key, obj);
                        }
                    }
                }
            }
            return obj;
        }

        function forEachSorted(obj, iterator, context) {
            var keys = Object.keys(obj).sort();
            for (var i = 0; i < keys.length; i++) {
                iterator.call(context, obj[keys[i]], keys[i]);
            }
            return keys;
        }

        function isArrayLike(obj) {
            if (obj == null || angular.isWindow(obj)) {
                return false;
            }

            // Support: iOS 8.2 (not reproducible in simulator)
            // "length" in obj used to prevent JIT error (gh-11508)
            var length = "length" in Object(obj) && obj.length;

            if (obj.nodeType === true && length) {
                return true;
            }

            return angular.isString(obj) || angular.isArray(obj) || length === 0 ||
                typeof length === 'number' && length > 0 && (length - 1) in obj;
        }

        function toJson(obj, pretty) {
            if (typeof obj === 'undefined') return undefined;
            if (!angular.isNumber(pretty)) {
                pretty = pretty ? 2 : null;
            }
            return JSON.stringify(obj, toJsonReplacer, pretty);
        }

        return function (params) {
            if (!params) return '';
            var parts = [];
            serialize(params, '', true);
            return parts.join('&');

            function serialize(toSerialize, prefix, topLevel) {
                if (toSerialize === null || angular.isUndefined(toSerialize)) return;
                if (angular.isArray(toSerialize)) {
                    forEach(toSerialize, function (value, index) {
                        serialize(value, prefix + '[' + (angular.isObject(value) ? index : '') + ']');
                    });
                } else if (angular.isObject(toSerialize) && !angular.isDate(toSerialize)) {
                    forEachSorted(toSerialize, function (value, key) {
                        serialize(value, prefix +
                            (topLevel ? '' : '.') +
                            key +
                            (topLevel ? '' : ''));
                    });
                } else {
                    parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
                }
            }
        };
    })
    .factory('apazUtil', function(toaster){
        var apazUtil = {
            buildPageList: function(pageInfo) {
                var _pageList = [];

                var currentPage = pageInfo.number,begin = 0,
                    end = pageInfo.totalPages,flag = end > 8;

                if (flag) {
                    begin = currentPage - 2 > 0 ? currentPage - 2 : 0;
                    end = currentPage + 3 > end ? end : currentPage + 3;

                    if(currentPage < 2 && end + 2 - currentPage < pageInfo.totalPages) {
                        end += 2 - currentPage;
                    }

                    if(currentPage + 2 >= pageInfo.totalPages && end - begin > 0) {
                        begin -= 2 - (pageInfo.totalPages - currentPage - 1);
                    }
                }
                for (;begin < end;begin++) {
                    _pageList.push({
                        index:begin,
                        value:begin + 1
                    });
                }
                if (flag) {
                    if(end < pageInfo.totalPages - 1) {
                        _pageList.push({index:-2,value:'...'});
                    }

                    if(end < pageInfo.totalPages) {
                        _pageList.push({index:pageInfo.totalPages-1,value:pageInfo.totalPages});
                    }
                }

                if(_pageList.length == 0){
                    _pageList.push({index:0,value:1});
                }

                return _pageList;
            },
            pageChange: function (num, pageInfo, callback, args) {
                if (num == undefined || pageInfo == undefined || num < 0 || num >= pageInfo.totalPages || pageInfo.number == num) {
                    return;
                }

                pageInfo.number = num;
                pageInfo.pageList = apazUtil.buildPageList(pageInfo);

                callback && callback.apply(this, args);
            },
            pageChangeTo: function (currPage, pageInfo, callback, args) {
                var _n = Number(currPage);
                if (isNaN(_n) || _n == undefined || _n <= 0 || _n > pageInfo.totalPages) {
                    currPage = 1;
                    toaster.warning('页码超过范围，请确认！');
                }

                apazUtil.pageChange(currPage - 1,pageInfo,callback,args);
            }
        };

        return apazUtil;
    });
